package com.xuanheng.utils.http;

import com.alibaba.fastjson.JSON;
import com.xuanheng.utils.LogUtils;
import com.xuanheng.utils.http.async.IResponseHandler;


import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

/**
 * Created by liyh on 2017/1/18.
 */

public class ParseDataListener<T> implements IResponseHandler {
    private Class clazz;

    public ParseDataListener() {
        this.clazz = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }


    @Override
    public void onStart() {

    }

    @Override
    public void onFinished() {

    }

    @Override
    public void onTimeout() {
    }

    @Override
    public void onCancelled() {

    }

    @Override
    public void onProgress(int current, int total) {

    }

    @Override
    public void onSuccess(int statusCode, Map<String, List<String>> headers, String response) {
        try {
            if(response!=null){
                LogUtils.de("HttpGetRequest",response);
            }
            T object = (T) JSON.parseObject(response, clazz);
            if (object != null) {
                onParseDataSuccess(object);
            } else {
                LogUtils.de("HttpGetRequest","json反序列化失败");
                onFailure(205, null, null, new Throwable("json反序列化失败"));
            }
        } catch (Exception e) {
            onFailure(205, null, null, new Throwable("json反序列化失败"));
            LogUtils.de("HttpGetRequest","解析错误");
        }

    }

    @Override
    public void onFailure(int statusCode, Map<String, List<String>> headers, String responseString, Throwable throwable) {
    }

    public void onParseDataSuccess(T result) {

    }




}
